﻿using RXY_Mall.Core;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using System;
using System.Linq;

namespace RXY_Mall.Services.Base
{
    public class BaseService
    {
        /// <summary>
        /// 短信是否正确
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="code">验证码</param>
        /// <param name="type">验证类型</param>
        /// <param name="error">错误</param>
        /// <returns></returns>
        public bool IsCheckSms(string mobile, string code, SMSType type, out string error)
        {
            bool flag = false;
            error = "";
            try
            {
                if (!string.IsNullOrEmpty(AppConfig.EverythingVerifyCode) && code == AppConfig.EverythingVerifyCode)
                {
                    LogHelper.WriteLog("该用户使用万能验证码进行用户注册，手机号：" + mobile);
                    flag = true;
                    return flag;
                }

                using (RXY_MallContext db = new RXY_MallContext())
                {
                    var usercode = db.gw_base_smses.OrderByDescending(c => c.id).FirstOrDefault(c => c.mobile == mobile && c.status == 0 && c.type == (byte)type);

                    if (usercode == null)
                    {
                        error = "验证码错误";
                        return flag;
                    }
                    if (DateTime.Now > usercode.eff_time)
                    {
                        error = "验证码过期,请重新获取";
                        return flag;
                    }
                    if (usercode.count > 3)
                    {
                        //验证过
                        usercode.status = 1;
                        db.Entry(usercode).Property(u => u.status).IsModified = true;
                        db.SaveChanges();

                        error = "验证码已超过验证次数,请重新获取";
                        return flag;
                    }
                    
                    if (code != usercode.code)
                    {
                        usercode.count += 1;
                        db.Entry(usercode).Property(u => u.count).IsModified = true;
                        db.SaveChanges();

                        error = "验证码错误";
                        return flag;
                    }
                    //验证过
                    usercode.count += 1;
                    db.Entry(usercode).Property(u => u.count).IsModified = true;
                    usercode.status = 1;
                    db.Entry(usercode).Property(u => u.status).IsModified = true;
                    db.SaveChanges();
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            return flag;
        }
    }
}
